package client.global.commlib.network.converterfactory

import com.google.gson.Gson
import com.google.gson.TypeAdapter

import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.Buffer
import retrofit2.Converter

import java.io.OutputStreamWriter
import java.io.Writer
import java.nio.charset.Charset

class CustomGsonRequestBodyConverter : Converter<Any?, RequestBody?> {
    private val MEDIA_TYPE = "application/json; charset=UTF-8".toMediaType()
    private val UTF_8 = Charset.forName("UTF-8")

    val gson: Gson?
    val adapter: TypeAdapter<Any>?

    constructor(gson: Gson?, adapter: TypeAdapter<Any>?) {
        this.gson = gson
        this.adapter = adapter
    }

    override fun convert(value: Any?): RequestBody? {
        val buffer = Buffer()
        val writer: Writer =
            OutputStreamWriter(buffer.outputStream(), UTF_8)
        val jsonWriter = gson?.newJsonWriter(writer)
        adapter?.write(jsonWriter, value)
        jsonWriter?.close()
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString())
    }
}